﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework;

/**
 * 创建时间：2014/12/27 20:02:10
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace ComicIsland.Common
{
    public class Variables
    {
        private const string AppManifestName = "WMAppManifest.xml";
        private const string AppNodeName = "App";
        private static ProgressIndicator Indicator = new ProgressIndicator();
        private static readonly IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();


        public static byte[] ContentTypebyCode(string sType)
        {
            string text = "";
            if (sType != null)
            {
                if (!(sType == "image/jpeg"))
                {
                    if (!(sType == "image/png"))
                    {
                        if (sType == "image/webp")
                        {
                            text = "WBP";
                        }
                    }
                    else
                    {
                        text = "PNG";
                    }
                }
                else
                {
                    text = "JPG";
                }
            }
            return Encoding.UTF8.GetBytes(text);
        }
        public static string CodeByContentType(byte[] sbytes)
        {
            if (sbytes.Length <= 0)
            {
                return "";
            }
            byte[] bytesByLength = Variables.GetBytesByLength(sbytes, sbytes.Length - 3, 3);
            return Encoding.UTF8.GetString(bytesByLength, 0, bytesByLength.Length);
        }
        public static byte[] GetBytesByLength(byte[] bytes, int offset, int count)
        {
            List<byte> list = new List<byte>();
            for (int i = 0; i < bytes.Length; i++)
            {
                byte b = bytes[i];
                list.Add(b);
            }
            byte[] array = new byte[count];
            for (int j = 0; j < count; j++)
            {
                array[j] = list[offset];
                offset++;
            }
            return array;
        }

        public static void SetProgressIndicator(DependencyObject element, bool isVisible, string sTitle = "加载数据...")
        {
            if (isVisible)
            {
                Variables.Indicator.Text = sTitle;
                Variables.Indicator.IsIndeterminate = true;
                Variables.Indicator.IsVisible = (true);
                SystemTray.SetOpacity(Variables.Indicator, 1.0);
                SystemTray.SetProgressIndicator(element, Variables.Indicator);
                return;
            }
            Variables.Indicator.IsVisible = (false);
            Variables.Indicator.IsIndeterminate = (false);
            SystemTray.SetOpacity(Variables.Indicator, 0.0);
        }
        public static T FindChildOfType<T>(DependencyObject root) where T : class
        {
            Queue<DependencyObject> queue = new Queue<DependencyObject>();
            queue.Enqueue(root);
            while (queue.Count() > 0)
            {
                DependencyObject dependencyObject = queue.Dequeue();
                int num = VisualTreeHelper.GetChildrenCount(dependencyObject) - 1;
                while (0 <= num)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(dependencyObject, num);
                    T t = child as T;
                    if (t != null)
                    {
                        return t;
                    }
                    queue.Enqueue(child);
                    num--;
                }
            }
            return default(T);
        }
        public static List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            List<T> list = new List<T>();
            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child is T)
                {
                    T t = (T)((object)child);
                    if (t.Name == name || string.IsNullOrEmpty(name))
                    {
                        list.Add((T)((object)child));
                    }
                }
                list.AddRange(Variables.GetChildObjects<T>(child, ""));
            }
            return list;
        }
        private static void ClearValue(DependencyObject oObject, DependencyProperty oProperty)
        {
            object obj = oObject.ReadLocalValue(oProperty);
            if (obj != DependencyProperty.UnsetValue)
            {
                oObject.ClearValue(oProperty);
            }
        }
        private static void ClearPivotItemDependencyValues(PivotItem oPivotItem)
        {
            Variables.ClearValue(oPivotItem, FrameworkElement.ActualHeightProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.ActualWidthProperty);
            Variables.ClearValue(oPivotItem, UIElement.AllowDropProperty);
            Variables.ClearValue(oPivotItem, Control.BackgroundProperty);
            Variables.ClearValue(oPivotItem, Control.BorderBrushProperty);
            Variables.ClearValue(oPivotItem, Control.BorderThicknessProperty);
            Variables.ClearValue(oPivotItem, UIElement.CacheModeProperty);
            Variables.ClearValue(oPivotItem, Control.CharacterSpacingProperty);
            Variables.ClearValue(oPivotItem, UIElement.ClipProperty);
            Variables.ClearValue(oPivotItem, ContentControl.ContentProperty);
            Variables.ClearValue(oPivotItem, ContentControl.ContentTemplateProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.CursorProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.DataContextProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.FlowDirectionProperty);
            Variables.ClearValue(oPivotItem, Control.FontFamilyProperty);
            Variables.ClearValue(oPivotItem, Control.FontSizeProperty);
            Variables.ClearValue(oPivotItem, Control.FontStretchProperty);
            Variables.ClearValue(oPivotItem, Control.FontStyleProperty);
            Variables.ClearValue(oPivotItem, Control.FontWeightProperty);
            Variables.ClearValue(oPivotItem, Control.ForegroundProperty);
            Variables.ClearValue(oPivotItem, PivotItem.HeaderProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.HeightProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.HorizontalAlignmentProperty);
            Variables.ClearValue(oPivotItem, Control.HorizontalContentAlignmentProperty);
            Variables.ClearValue(oPivotItem, Control.IsEnabledProperty);
            Variables.ClearValue(oPivotItem, UIElement.IsHitTestVisibleProperty);
            Variables.ClearValue(oPivotItem, Control.IsTabStopProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.LanguageProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.MarginProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.MaxHeightProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.MaxWidthProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.MinHeightProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.MinWidthProperty);
            Variables.ClearValue(oPivotItem, UIElement.OpacityMaskProperty);
            Variables.ClearValue(oPivotItem, UIElement.OpacityProperty);
            Variables.ClearValue(oPivotItem, Control.PaddingProperty);
            Variables.ClearValue(oPivotItem, UIElement.ProjectionProperty);
            Variables.ClearValue(oPivotItem, UIElement.RenderTransformOriginProperty);
            Variables.ClearValue(oPivotItem, UIElement.RenderTransformProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.StyleProperty);
            Variables.ClearValue(oPivotItem, Control.TabIndexProperty);
            Variables.ClearValue(oPivotItem, Control.TabNavigationProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.TagProperty);
            Variables.ClearValue(oPivotItem, Control.TemplateProperty);
            Variables.ClearValue(oPivotItem, UIElement.UseLayoutRoundingProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.UseOptimizedManipulationRoutingProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.VerticalAlignmentProperty);
            Variables.ClearValue(oPivotItem, Control.VerticalContentAlignmentProperty);
            Variables.ClearValue(oPivotItem, UIElement.VisibilityProperty);
            Variables.ClearValue(oPivotItem, FrameworkElement.WidthProperty);
        }
        public static void ClearPivotDependencyValues(Pivot oPivot)
        {
            using (IEnumerator<object> enumerator = oPivot.Items.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    PivotItem oPivotItem = (PivotItem)enumerator.Current;
                    Variables.ClearPivotItemDependencyValues(oPivotItem);
                }
            }
            Variables.ClearValue(oPivot, FrameworkElement.ActualHeightProperty);
            Variables.ClearValue(oPivot, FrameworkElement.ActualWidthProperty);
            Variables.ClearValue(oPivot, UIElement.AllowDropProperty);
            Variables.ClearValue(oPivot, Control.BackgroundProperty);
            Variables.ClearValue(oPivot, Control.BorderBrushProperty);
            Variables.ClearValue(oPivot, Control.BorderThicknessProperty);
            Variables.ClearValue(oPivot, UIElement.CacheModeProperty);
            Variables.ClearValue(oPivot, Control.CharacterSpacingProperty);
            Variables.ClearValue(oPivot, UIElement.ClipProperty);
            Variables.ClearValue(oPivot, FrameworkElement.CursorProperty);
            Variables.ClearValue(oPivot, FrameworkElement.DataContextProperty);
            Variables.ClearValue(oPivot, ItemsControl.DisplayMemberPathProperty);
            Variables.ClearValue(oPivot, FrameworkElement.FlowDirectionProperty);
            Variables.ClearValue(oPivot, Control.FontFamilyProperty);
            Variables.ClearValue(oPivot, Control.FontSizeProperty);
            Variables.ClearValue(oPivot, Control.FontStretchProperty);
            Variables.ClearValue(oPivot, Control.FontStyleProperty);
            Variables.ClearValue(oPivot, Control.FontWeightProperty);
            Variables.ClearValue(oPivot, Control.ForegroundProperty);
            Variables.ClearValue(oPivot, Pivot.HeaderTemplateProperty);
            Variables.ClearValue(oPivot, FrameworkElement.HeightProperty);
            Variables.ClearValue(oPivot, FrameworkElement.HorizontalAlignmentProperty);
            Variables.ClearValue(oPivot, Control.HorizontalContentAlignmentProperty);
            Variables.ClearValue(oPivot, Control.IsEnabledProperty);
            Variables.ClearValue(oPivot, UIElement.IsHitTestVisibleProperty);
            Variables.ClearValue(oPivot, Control.IsTabStopProperty);
            Variables.ClearValue(oPivot, Pivot.ItemContainerStyleProperty);
            Variables.ClearValue(oPivot, ItemsControl.ItemsPanelProperty);
            Variables.ClearValue(oPivot, ItemsControl.ItemsSourceProperty);
            Variables.ClearValue(oPivot, ItemsControl.ItemTemplateProperty);
            Variables.ClearValue(oPivot, FrameworkElement.LanguageProperty);
            Variables.ClearValue(oPivot, FrameworkElement.MarginProperty);
            Variables.ClearValue(oPivot, FrameworkElement.MaxHeightProperty);
            Variables.ClearValue(oPivot, FrameworkElement.MaxWidthProperty);
            Variables.ClearValue(oPivot, FrameworkElement.MinHeightProperty);
            Variables.ClearValue(oPivot, FrameworkElement.MinWidthProperty);
            Variables.ClearValue(oPivot, UIElement.OpacityMaskProperty);
            Variables.ClearValue(oPivot, UIElement.OpacityProperty);
            Variables.ClearValue(oPivot, Control.PaddingProperty);
            Variables.ClearValue(oPivot, UIElement.ProjectionProperty);
            Variables.ClearValue(oPivot, UIElement.RenderTransformOriginProperty);
            Variables.ClearValue(oPivot, UIElement.RenderTransformProperty);
            Variables.ClearValue(oPivot, Pivot.SelectedIndexProperty);
            Variables.ClearValue(oPivot, FrameworkElement.StyleProperty);
            Variables.ClearValue(oPivot, Control.TabIndexProperty);
            Variables.ClearValue(oPivot, Control.TabNavigationProperty);
            Variables.ClearValue(oPivot, FrameworkElement.TagProperty);
            Variables.ClearValue(oPivot, Control.TemplateProperty);
            Variables.ClearValue(oPivot, Pivot.TitleProperty);
        }
        public static void ClearLongListSelectorDependencyValues(LongListSelector oList)
        {
            Variables.ClearValue(oList, FrameworkElement.ActualHeightProperty);
            Variables.ClearValue(oList, FrameworkElement.ActualWidthProperty);
            Variables.ClearValue(oList, UIElement.AllowDropProperty);
            Variables.ClearValue(oList, Control.BackgroundProperty);
            Variables.ClearValue(oList, Control.BorderBrushProperty);
            Variables.ClearValue(oList, Control.BorderThicknessProperty);
            Variables.ClearValue(oList, UIElement.CacheModeProperty);
            Variables.ClearValue(oList, Control.CharacterSpacingProperty);
            Variables.ClearValue(oList, UIElement.ClipProperty);
            Variables.ClearValue(oList, FrameworkElement.CursorProperty);
            Variables.ClearValue(oList, FrameworkElement.DataContextProperty);
            Variables.ClearValue(oList, FrameworkElement.FlowDirectionProperty);
            Variables.ClearValue(oList, Control.FontFamilyProperty);
            Variables.ClearValue(oList, Control.FontSizeProperty);
            Variables.ClearValue(oList, Control.FontStretchProperty);
            Variables.ClearValue(oList, Control.FontStyleProperty);
            Variables.ClearValue(oList, Control.FontWeightProperty);
            Variables.ClearValue(oList, Control.ForegroundProperty);
            Variables.ClearValue(oList, LongListSelector.GridCellSizeProperty);
            Variables.ClearValue(oList, LongListSelector.GroupFooterTemplateProperty);
            Variables.ClearValue(oList, LongListSelector.GroupHeaderTemplateProperty);
            Variables.ClearValue(oList, FrameworkElement.HeightProperty);
            Variables.ClearValue(oList, LongListSelector.HideEmptyGroupsProperty);
            Variables.ClearValue(oList, FrameworkElement.HorizontalAlignmentProperty);
            Variables.ClearValue(oList, Control.HorizontalContentAlignmentProperty);
            Variables.ClearValue(oList, Control.IsEnabledProperty);
            Variables.ClearValue(oList, LongListSelector.IsGroupingEnabledProperty);
            Variables.ClearValue(oList, UIElement.IsHitTestVisibleProperty);
            Variables.ClearValue(oList, Control.IsTabStopProperty);
            Variables.ClearValue(oList, LongListSelector.ItemsSourceProperty);
            Variables.ClearValue(oList, LongListSelector.ItemTemplateProperty);
            Variables.ClearValue(oList, LongListSelector.JumpListStyleProperty);
            Variables.ClearValue(oList, FrameworkElement.LanguageProperty);
            Variables.ClearValue(oList, LongListSelector.ListFooterProperty);
            Variables.ClearValue(oList, LongListSelector.ListFooterTemplateProperty);
            Variables.ClearValue(oList, LongListSelector.ListHeaderProperty);
            Variables.ClearValue(oList, LongListSelector.ListHeaderTemplateProperty);
            Variables.ClearValue(oList, FrameworkElement.MarginProperty);
            Variables.ClearValue(oList, FrameworkElement.MaxHeightProperty);
            Variables.ClearValue(oList, FrameworkElement.MaxWidthProperty);
            Variables.ClearValue(oList, FrameworkElement.MinHeightProperty);
            Variables.ClearValue(oList, FrameworkElement.MinWidthProperty);
            Variables.ClearValue(oList, UIElement.OpacityMaskProperty);
            Variables.ClearValue(oList, UIElement.OpacityProperty);
            Variables.ClearValue(oList, Control.PaddingProperty);
            Variables.ClearValue(oList, UIElement.ProjectionProperty);
            Variables.ClearValue(oList, UIElement.RenderTransformOriginProperty);
            Variables.ClearValue(oList, UIElement.RenderTransformProperty);
            Variables.ClearValue(oList, FrameworkElement.StyleProperty);
            Variables.ClearValue(oList, Control.TabIndexProperty);
            Variables.ClearValue(oList, Control.TabNavigationProperty);
            Variables.ClearValue(oList, FrameworkElement.TagProperty);
            Variables.ClearValue(oList, Control.TemplateProperty);
            Variables.ClearValue(oList, UIElement.UseLayoutRoundingProperty);
            Variables.ClearValue(oList, FrameworkElement.UseOptimizedManipulationRoutingProperty);
            Variables.ClearValue(oList, FrameworkElement.VerticalAlignmentProperty);
            Variables.ClearValue(oList, Control.VerticalContentAlignmentProperty);
            Variables.ClearValue(oList, UIElement.VisibilityProperty);
            Variables.ClearValue(oList, FrameworkElement.WidthProperty);
        }
        public static string GetVersion()
        {
            try
            {
                XElement root = XDocument.Load("WMAppManifest.xml").Root;
                return root.Element("App").Attribute("Version").Value;
            }
            catch
            {
            }
            return "";            
        }
        private static string GetManifestAttributeValue(string attributeName)
        {
            XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
            xmlReaderSettings.XmlResolver = (new XmlXapResolver());
            XmlReaderSettings xmlReaderSettings2 = xmlReaderSettings;
            string attribute;
            using (XmlReader xmlReader = XmlReader.Create("WMAppManifest.xml", xmlReaderSettings2))
            {
                xmlReader.ReadToDescendant("App");
                if (!xmlReader.IsStartElement())
                {
                    throw new FormatException("WMAppManifest.xml is missing App");
                }
                attribute = xmlReader.GetAttribute(attributeName);
            }
            return attribute;
        }
        private static async Task<Version> GetUpdatedVersion()
        {
            string name = CultureInfo.CurrentUICulture.Name;
            string requestUri = string.Format("http://marketplaceedgeservice.windowsphone.com/v8/catalog/apps/{0}?os={1}&cc={2}&oc=&lang={3}​", new object[]
			{
				"Constants.AppId",
				Environment.OSVersion.Version,
				name.Substring(name.Length - 2).ToUpperInvariant(),
				name
			});
            Version result;
            try
            {
                //HttpClient httpClient = new HttpClient();
                //HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(requestUri);
                //httpResponseMessage.EnsureSuccessStatusCode();
                //using (Stream stream = await httpResponseMessage.Content.ReadAsStreamAsync())
                //{
                //    using (XmlReader xmlReader = XmlReader.Create(stream))
                //    {
                //        xmlReader.MoveToContent();
                //        string text = xmlReader.LookupNamespace("a");
                //        xmlReader.ReadToFollowing("entry", text);
                //        xmlReader.ReadToDescendant("version");
                //        result = new Version(xmlReader.ReadElementContentAsString());
                //        return result;
                //    }
                //}
            }
            catch
            {
            }
            result = new Version("1.0.0.0");
            return result;
        }
        public static async void CheckAppVersion(bool bUpate = true)
        {
            string version = Variables.GetVersion();
            if (!string.IsNullOrEmpty(version))
            {
                Version version2 = new Version(version);
                Version version3 = await Variables.GetUpdatedVersion();
                if (version3 > version2)
                {
                    if (MessageBox.Show("检测到商店有新版本，要立即更新吗？", "版本升级", (MessageBoxButton)1) == (MessageBoxResult)1)
                    {
                        new MarketplaceDetailTask().Show();
                    }
                }
                else
                {
                    if (!bUpate)
                    {
                        //ToastUtils.Show("已经最新版本yoo(ΦωΦ)");
                    }
                }
            }
        }

    }
}

